import { Modal, Drawer, Button, message } from 'antd'
import { getVersionList } from '@/apis/accessManagement/setup'
import { deleteVersion } from '@/apis/accessManagement/setup'
import ExcelTable from '@components/exportExcel'
import FormView from '@/pages/setting/appVersionManage/components/FormView'
import { useRef, useState, useEffect } from 'react'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import { observer } from 'mobx-react'
import { storeGlobalUser } from '@/store/globalUser'
// import { toJS } from 'mobx'
import routerId from '@config/routes/routerId'
const AppVersionManage: React.FC = () => {
  const { authMenuPaths } = storeGlobalUser
  // console.log(toJS(authMenuPaths), 'authMenuPaths')
  useRef<ActionType>()
  useRef<ProFormInstance>()
  const actionRef = useRef()
  const [tableItem, setTableItem] = useState(null)
  const [detailDrawer, setDetailDrawer] = useState(false)
  const [drawerTitle, setDrawerTitle] = useState('')
  const [messageApi, contextHolder] = message.useMessage()

  const addVersionAuth = authMenuPaths[routerId.addAppVersion]
  const editVersionAuth = authMenuPaths[routerId.editAppVersion]
  const delVersionAuth = authMenuPaths[routerId.delAppVersion]

  // const addVersionAuth = authMenuPaths[routerId.addAppVersion]
  function showAddDrawer(item: any) {
    if (Object.keys(item).length === 0) {
      setDrawerTitle('新增App版本')
    } else {
      setDrawerTitle('查看App版本')
    }
    setTableItem(item)
    setDetailDrawer(true)
  }

  function onCloseDrawer() {
    setDetailDrawer(false)
    actionRef.current?.reloadAndRest()
  }

  // 提交删除版本
  const subDeleteVersion = async (params: any) => {
    // console.log(params)
    // const { versionId } = params;
    try {
      const response = await deleteVersion({
        versionId: params.versionId
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          await messageApi.open({
            type: 'success',
            content: '删除成功',
            duration: 2
          })
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`删除失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    }
  }

  return (
    <>
      {contextHolder}
      <ExcelTable
        actionRef={actionRef}
        requestFn={params => {
          const { pageNum, pageSize, productName, platform, forceUpgrade, ...newParams } = params // 处理所需参数名
          const data = getVersionList({
            ...newParams,
            pagination: { pageNumber: pageNum, showNumber: pageSize },
            productName: productName,
            platform: parseInt(platform),
            forceUpgrade: parseInt(forceUpgrade)
          })
          return data
        }}
        rowSelection={false}
        toolBarRenderFn={() => [
          addVersionAuth && (
            <Button key="add" onClick={() => showAddDrawer({})}>
              添加
            </Button>
          )
        ]}
        columns={[
          /** search */
          {
            title: '产品名称',
            dataIndex: 'productName',
            hideInTable: true
          },
          {
            title: '平台',
            dataIndex: 'platform',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
              // null: '全部',
              1: 'Android',
              2: 'Ios',
              3: '全部'
            }
          },
          {
            title: '版本号',
            dataIndex: 'versionCode',
            hideInTable: true
          },
          {
            title: '强制更新',
            dataIndex: 'forceUpgrade',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
              1: '是',
              2: '否'
            }
          },
          //   {
          //     title: '操作人',
          //     dataIndex: 'keyword6',
          //     hideInTable: true
          //   },
          //   {
          //     title: '操作时间',
          //     dataIndex: 'keyword7',
          //     valueType: 'dateRange',
          //     hideInTable: true
          //   },
          /** table */
          {
            title: '序号',
            valueType: 'index',
            hideInSearch: true,
            width: 60
          },
          {
            title: '产品名称',
            dataIndex: 'productName',
            hideInSearch: true
          },
          {
            title: '平台',
            dataIndex: 'platform',
            hideInSearch: true,
            render: (_, record) =>
              record.platform === 1 ? 'Android' : record.platform === 2 ? 'Ios' : 'Android、Ios'
          },
          {
            title: '版本号',
            dataIndex: 'versionCode',
            hideInSearch: true
          },
          {
            title: '更新描述',
            dataIndex: 'desc',
            hideInSearch: true,
            onCell: () => ({
              style: {
                maxWidth: '300px', // 最大宽度限制
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
              }
            })
            // width:300,
            // ellipsis:true,
          },
          {
            title: 'Ios下载地址',
            dataIndex: 'iosDownloadUrl',
            hideInSearch: true
          },
          {
            title: 'Android下载地址',
            dataIndex: 'androidDownloadUrl',
            hideInSearch: true
          },
          {
            title: '是否强推',
            dataIndex: 'showForceUpgrade',
            hideInSearch: true,
            render: (_, record) => (record.showForceUpgrade === 1 ? '是' : '否')
          },
          {
            title: '是否提示更新',
            dataIndex: 'showUpgradeTip',
            hideInSearch: true,
            render: (_, record) => (record.showUpgradeTip === 1 ? '是' : '否')
          },
          {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_, record) => [
              editVersionAuth && (
                <a key="update" onClick={() => showAddDrawer(record)}>
                  修改
                </a>
              ),
              delVersionAuth && (
                <a
                  key="delete"
                  onClick={() => {
                    Modal.warning({
                      title: '提示',
                      content: '确定删除此版本吗?',
                      okText: '确定',
                      okCancel: true,
                      onOk() {
                        subDeleteVersion(record)
                        // console.log('Confirmed:onOk ')
                      }
                    })
                  }}
                >
                  删除
                </a>
              )
            ]
          }
        ]}
      />
      <Drawer title={drawerTitle} onClose={onCloseDrawer} open={detailDrawer} destroyOnClose>
        <FormView item={tableItem} onClose={onCloseDrawer}></FormView>
      </Drawer>
    </>
  )
}

export default observer(AppVersionManage)
